﻿Imports System.Xml
Imports System.IO
Imports System.Text
Imports SQLtoASPX.Globals
Imports SQLtoASPX.Support
Imports System.Data.SqlClient

'Persistence
'grd
'add to grd
'xml save
'Close Button


Public Class ClassTabPage
    Inherits System.Windows.Forms.TabPage

    Friend WithEvents cmdGenerate As System.Windows.Forms.Button
    Friend WithEvents Label20 As System.Windows.Forms.Label
    Friend WithEvents txtPrivateMemberPrefix As System.Windows.Forms.TextBox
    Friend WithEvents Label19 As System.Windows.Forms.Label
    Friend WithEvents cboClassGenerationStyle As System.Windows.Forms.ComboBox
    'Friend WithEvents cboPrimaryKey As System.Windows.Forms.ComboBox
    Friend WithEvents txtPrefix As System.Windows.Forms.TextBox
    Friend WithEvents Label16 As System.Windows.Forms.Label
    Friend WithEvents lblPrimaryKey As System.Windows.Forms.Label
    Friend WithEvents grd As System.Windows.Forms.DataGridView
    Friend WithEvents ColumnNames As System.Windows.Forms.DataGridViewTextBoxColumn
    Friend WithEvents cmdCloseButton As New System.Windows.Forms.Button
    Friend WithEvents cmdAddNew As New System.Windows.Forms.Button


    Public DatabaseName As String = ""
    Public dt As DataTable = Nothing
    'Public gTableName As String = ""
    Public ServerName As String = ""
    Public TableDatabaseObject As DatabaseObject

    Public IndexKeys As New List(Of String)
    Public IndexKeysSortedTypeList As New List(Of String)
    Public ColumnList As New Dictionary(Of String, Column)
    Public BadList As New List(Of String)

    Public DatabaseServer As DatabaseServer = Nothing

    Private mTreeNode As TreeNode
    Public Property TreeNode() As TreeNode
        Get
            Return mTreeNode
        End Get
        Set(ByVal value As TreeNode)
            mTreeNode = value
        End Set
    End Property

    Public Sub New()

        'Me.Controls.Add(New DataGridView)
        InitializeComponent()
        cboClassGenerationStyle.Items.Add("Property")
        cboClassGenerationStyle.SelectedIndex = 0

        'cboPrimaryKey.Items.Add("Public")
        'cboPrimaryKey.Items.Add("Property")
        'cboPrimaryKey.SelectedIndex = 1

        '  LoadGrid(TreeNode)



    End Sub

    Private Sub InitializeComponent()
        Me.Label20 = New System.Windows.Forms.Label
        Me.txtPrivateMemberPrefix = New System.Windows.Forms.TextBox
        Me.Label19 = New System.Windows.Forms.Label
        Me.cboClassGenerationStyle = New System.Windows.Forms.ComboBox
        Me.txtPrefix = New System.Windows.Forms.TextBox
        Me.Label16 = New System.Windows.Forms.Label
        Me.cmdGenerate = New System.Windows.Forms.Button
        Me.lblPrimaryKey = New System.Windows.Forms.Label
        Me.grd = New System.Windows.Forms.DataGridView
        CType(Me.grd, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.ColumnNames = New System.Windows.Forms.DataGridViewTextBoxColumn
        Me.cmdCloseButton = New System.Windows.Forms.Button
        Me.cmdAddNew = New System.Windows.Forms.Button

        Me.SuspendLayout()

        Me.cmdCloseButton.Anchor = System.Windows.Forms.AnchorStyles.Top Or AnchorStyles.Right
        Me.cmdCloseButton.Location = New System.Drawing.Point(170, 5)
        Me.cmdCloseButton.Name = "cmdCloseButton"
        Me.cmdCloseButton.Size = New System.Drawing.Size(23, 23)
        Me.cmdCloseButton.TabIndex = 0
        Me.cmdCloseButton.Text = "X"

        Me.cmdAddNew.Location = New System.Drawing.Point(630, 83)
        Me.cmdAddNew.Name = "cmdAddNew"
        Me.cmdAddNew.Size = New System.Drawing.Size(145, 23)
        Me.cmdAddNew.TabIndex = 0
        Me.cmdAddNew.Text = "Add Additional Constructor"

        Me.ColumnNames.DataPropertyName = "ColumnNames"
        Me.ColumnNames.HeaderText = "Constructors to Generate"
        Me.ColumnNames.Name = "ColumnNames"
        Me.ColumnNames.ReadOnly = True
        Me.ColumnNames.Width = 450

        'grd
        Me.grd.AllowUserToAddRows = False
        Me.grd.AllowUserToDeleteRows = False
        Me.grd.AutoGenerateColumns = False
        Me.grd.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
        Me.grd.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.ColumnNames})
        'Me.grd.Dock = System.Windows.Forms.DockStyle.Fill
        Me.grd.Location = New System.Drawing.Point(0, 0)
        Me.grd.Name = "grd"
        Me.grd.Size = New System.Drawing.Size(500, 320)
        Me.grd.Location = New System.Drawing.Point(125, 83)
        Me.grd.TabIndex = 0


        '
        'cmdGenerate
        '
        Me.cmdGenerate.Anchor = System.Windows.Forms.AnchorStyles.Top
        Me.cmdGenerate.Location = New System.Drawing.Point(70, 0)
        Me.cmdGenerate.Name = "cmdGenerate"
        Me.cmdGenerate.Size = New System.Drawing.Size(75, 23)
        Me.cmdGenerate.TabIndex = 0
        Me.cmdGenerate.Text = "Generate"
        Me.Controls.Add(cmdGenerate)


        'Label20
        '
        Me.Label20.AutoSize = True
        Me.Label20.Location = New System.Drawing.Point(12, 55)
        Me.Label20.Name = "Label20"
        Me.Label20.Size = New System.Drawing.Size(107, 13)
        Me.Label20.TabIndex = 46
        Me.Label20.Text = "Private Member Pefix"
        '
        'txtPrivateMemberPrefix
        '
        Me.txtPrivateMemberPrefix.Location = New System.Drawing.Point(125, 55)
        Me.txtPrivateMemberPrefix.Name = "txtPrivateMemberPrefix"
        Me.txtPrivateMemberPrefix.Size = New System.Drawing.Size(100, 20)
        Me.txtPrivateMemberPrefix.TabIndex = 45
        Me.txtPrivateMemberPrefix.Text = "m"
        '
        'Label19
        '
        Me.Label19.AutoSize = True
        Me.Label19.Location = New System.Drawing.Point(12, 31)
        Me.Label19.Name = "Label19"
        Me.Label19.Size = New System.Drawing.Size(72, 13)
        Me.Label19.TabIndex = 44
        Me.Label19.Text = "Property Style"
        '
        'cboClassGenerationStyle
        '
        Me.cboClassGenerationStyle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cboClassGenerationStyle.FormattingEnabled = True
        Me.cboClassGenerationStyle.Location = New System.Drawing.Point(125, 31)
        Me.cboClassGenerationStyle.Name = "cboClassGenerationStyle"
        Me.cboClassGenerationStyle.Size = New System.Drawing.Size(281, 21)
        Me.cboClassGenerationStyle.TabIndex = 43
        '
        'txtPrefix
        '
        Me.txtPrefix.Location = New System.Drawing.Point(125, 7)
        Me.txtPrefix.Name = "txtPrefix"
        Me.txtPrefix.Size = New System.Drawing.Size(100, 20)
        Me.txtPrefix.TabIndex = 42
        Me.txtPrefix.Text = "C"
        '
        'Label16
        '
        Me.Label16.AutoSize = True
        Me.Label16.Location = New System.Drawing.Point(12, 7)
        Me.Label16.Name = "Label16"
        Me.Label16.Size = New System.Drawing.Size(61, 13)
        Me.Label16.TabIndex = 41
        Me.Label16.Text = "Class Prefix"
        Me.Label16.TextAlign = System.Drawing.ContentAlignment.TopCenter
        '
        Me.lblPrimaryKey.AutoSize = True
        Me.lblPrimaryKey.Location = New System.Drawing.Point(12, 80)
        Me.lblPrimaryKey.Name = "lblPrimaryKey"
        Me.lblPrimaryKey.Size = New System.Drawing.Size(61, 13)
        Me.lblPrimaryKey.TabIndex = 41
        Me.lblPrimaryKey.Text = "Constructors"
        Me.lblPrimaryKey.TextAlign = System.Drawing.ContentAlignment.TopCenter


        Me.Controls.Add(Me.Label20)
        Me.Controls.Add(Me.txtPrivateMemberPrefix)
        Me.Controls.Add(Me.Label19)
        Me.Controls.Add(Me.cboClassGenerationStyle)
        Me.Controls.Add(Me.txtPrefix)
        Me.Controls.Add(Me.Label16)
        Me.Controls.Add(Me.lblPrimaryKey)
        Me.Controls.Add(Me.grd)
        Me.Controls.Add(Me.cmdCloseButton)
        Me.Controls.Add(Me.cmdAddNew)

        CType(Me.grd, System.ComponentModel.ISupportInitialize).EndInit()

        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Private Sub SetComboBoxValue(ByVal cbo As ComboBox, ByVal Value As String)
        For i As Long = 0 To cbo.Items.Count - 1
            If cbo.Items(i)(1).ToString.ToUpper = Value.ToUpper Then
                cbo.SelectedIndex = i
                Exit Sub
            End If
        Next
    End Sub

    Private Sub SetComboBoxValue2(ByVal cbo As ComboBox, ByVal Value As String)
        For i As Long = 0 To cbo.Items.Count - 1
            If cbo.Items(i).ToString.ToUpper = Value.ToUpper Then
                cbo.SelectedIndex = i
                Exit Sub
            End If
        Next
    End Sub

    Private Function PrintCSRow(ByVal row As DataRow, ByVal CodeType As CodeTypeEnum, ByVal space As Space) As String
        Select Case SQLDataTypeToGenType(row("DataType"), CodeType).ToUpper
            Case "DATETIME"
                PrintCSRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = DateTime.Parse(Reader[""" & row("ColumnName") & """].ToString());" & vbCrLf
            Case "DOUBLE"
                PrintCSRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = double.Parse(Reader[""" & row("ColumnName") & """].ToString());" & vbCrLf
            Case "LONG"
                PrintCSRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = long.Parse(Reader[""" & row("ColumnName") & """].ToString());" & vbCrLf
            Case "BOOLEAN"
                PrintCSRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = bool.Parse(Reader[""" & row("ColumnName") & """].ToString());" & vbCrLf
            Case "STRING"
                PrintCSRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Reader[""" & row("ColumnName") & """].ToString();" & vbCrLf
            Case Else
                PrintCSRow = "//" & SQLDataTypeToGenType(row("DataType"), CodeType) & vbCrLf

                PrintCSRow = PrintCSRow & space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Reader[""" & row("ColumnName") & """];" & vbCrLf
        End Select
    End Function

    Private Function PrintVBRow(ByVal row As DataRow, ByVal CodeType As CodeTypeEnum, ByVal space As Space) As String
        Select Case SQLDataTypeToGenType(row("DataType"), CodeType).ToUpper
            Case "DATETIME"
                PrintVBRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = DateTime.Parse(Reader(""" & row("ColumnName") & """).ToString())" & vbCrLf
            Case "DOUBLE"
                PrintVBRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Double.Parse(Reader(""" & row("ColumnName") & """).ToString())" & vbCrLf
            Case "LONG"
                PrintVBRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Long.Parse(Reader(""" & row("ColumnName") & """).ToString())" & vbCrLf
            Case "BOOLEAN"
                PrintVBRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Boolean.Parse(Reader(""" & row("ColumnName") & """).ToString())" & vbCrLf
            Case "STRING"
                PrintVBRow = space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Reader(""" & row("ColumnName") & """).ToString()" & vbCrLf
            Case Else
                PrintVBRow = "'" & SQLDataTypeToGenType(row("DataType"), CodeType) & vbCrLf

                PrintVBRow = PrintVBRow & "            " & txtPrivateMemberPrefix.Text & row("ColumnName") & " = Reader(""" & row("ColumnName") & """);" & vbCrLf
        End Select
    End Function

    Private Function GetDataTable() As DataTable
        Dim dt As New DataTable
        Dim DataColumn As New DataColumn
        DataColumn.ColumnName = "ColumnName"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "DataType"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "ShowInMasterView"
        DataColumn.DataType = GetType(Boolean)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "ShowInDetailView"
        DataColumn.DataType = GetType(Boolean)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "SearchType"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "IsGroupColumn"
        DataColumn.DataType = GetType(Boolean)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "AllowNulls"
        DataColumn.DataType = GetType(Boolean)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "ColumnSize"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "IsIdentity"
        DataColumn.DataType = GetType(Boolean)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "ModifyLookup"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "LinkTableName"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "LinkTableKey"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)

        DataColumn = New DataColumn
        DataColumn.ColumnName = "LinkTableValue"
        DataColumn.DataType = GetType(String)
        dt.Columns.Add(DataColumn)
        Return dt
    End Function


    Public Sub LoadGrid(ByVal e As TreeNode)
        TreeNode = e

        Dim CurrentNode As TreeNode = e
        ' Dim CurrentTable As SQLtoASPX.Table = CurrentNode.Parent.Tag

        dt = GetDataTable()
        Dim ConnectionString As String = GetConnectionStringFromTreeNode(CurrentNode)
        DatabaseServer = GetDatabaseServerFromTreeNode(CurrentNode)
        Dim Connection As New SqlConnection(ConnectionString)
        Connection.Open()
        'Dim DB As SQLtoASPX.Database = CurrentNode.Parent.Tag
        DatabaseName = CurrentNode.Parent.Text
        ServerName = CurrentNode.Parent.Parent.Text
        TableDatabaseObject = CurrentNode.Tag

        Dim sql As String = "Select @@VERSION"

        Dim Command As New SqlCommand(sql, Connection)
        Dim Version As String = Command.ExecuteScalar

        Version = Replace(Version, "  ", " ")
        Dim VersionKeys() As String = Split(Version, " ")
        Dim VersionNumber As String = VersionKeys(3)

        'Dim VersionNumber As String = CurrentNode.Parent.Tag.Version
        'Dim DatabaseObject As DatabaseObject = CurrentNode.Tag

        'gTableName = CurrentNode.Text
        If VersionNumber = "2000" Then
            sql = "select c.*,o.* from " & DatabaseName & ".dbo.syscolumns c inner join " & DatabaseName & ".dbo.sysObjects o on o.id = c.id where o.Name = '" & TableDatabaseObject.Name & "' "
        Else
            sql = "select c.*,o.* from " & DatabaseName & ".dbo.syscolumns c inner join " & DatabaseName & ".dbo.sysObjects o on o.id = c.id inner join " & DatabaseName & ".sys.schemas s on s.schema_id = o.uid where o.Name = '" & TableDatabaseObject.Name & "' and s.Name = '" & TableDatabaseObject.Schema & "'"
        End If

        Command = New SqlCommand(sql, Connection)
        Debug.Print(sql)
        Dim Reader As SqlDataReader = Nothing
        Try
            Reader = Command.ExecuteReader
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try
        Dim TableID As Long = 0
        Do While Reader.Read
            TableID = Reader("ID")
            Dim column As New Column(Reader)
            Dim dr As DataRow = dt.NewRow

            dr("ColumnName") = column.Name
            dr("DataType") = column.GetColumnTypeName
            dr("ShowInMasterView") = column.ShowInMasterView
            dr("ShowInDetailView") = column.ShowInDetailView
            dr("SearchType") = column.SearchType
            dr("IsGroupColumn") = column.IsGroupColumn
            dr("AllowNulls") = column.AllowNulls
            dr("ColumnSize") = column.Length
            dr("IsIdentity") = column.IsIdentity
            dr("ModifyLookup") = "..."
            dt.Rows.Add(dr)
            ColumnList.Add(column.Name, column)
        Loop
        Reader.Close()



        Dim CurrentIndex As Long = 0
        Dim MarkIndex As Long = 0
        For Each row As DataRow In dt.Rows
            If row("IsIdentity") Then
                MarkIndex = CurrentIndex
                'IdentityColumnName = row("ColumnName")
            End If
            'cboPrimaryKey.Items.Add(row("columnName"))
            CurrentIndex = CurrentIndex + 1
            'AddColumn(row("ColumnName"), row("DataType"), row("AllowNulls"), row("ColumnSize"), "", row("ShowInDetailView"), row("IsIdentity"), False, False, row("ShowInMasterView"), row("SearchType"), row("IsGroupColumn"), "", "", "")
        Next
        'cboPrimaryKey.SelectedIndex = MarkIndex


        If IsNumeric(VersionNumber) Then
            If CLng(VersionNumber) >= 2005 Then
                sql = "select c.name from " & DatabaseName & ".sys.identity_columns c inner join " & DatabaseName & ".dbo.sysobjects t on c.object_id = t.id where t.id = " & TableID
                Command = New SqlCommand(sql, Connection)
                Reader = Command.ExecuteReader
                If Reader.Read Then
                    Dim AutonumberColumnName As String = Reader("Name")
                    If IndexKeys.Contains(AutonumberColumnName) = False Then
                        IndexKeys.Add(AutonumberColumnName)
                    End If
                End If
                Reader.Close()
                sql = "select c.Index_id,col.Name from " & DatabaseName & ".sys.index_columns c inner join " & DatabaseName & ".dbo.syscolumns col on col.id = c.object_id and c.column_id = col.colid where c.object_id = " & TableID & " order by c.Index_id, col.Name"
                Command = New SqlCommand(sql, Connection)
                Reader = Command.ExecuteReader
                Dim ColumnList As String = ""
                Dim LastindexID As String = ""
                Do While Reader.Read
                    If Len(LastindexID) > 0 And LastindexID <> CLng(Reader("Index_id")).ToString Then
                        If Len(ColumnList) > 0 Then
                            If IndexKeys.Contains(ColumnList) = False Then
                                IndexKeys.Add(ColumnList)
                                ColumnList = ""
                            End If
                        End If
                    End If
                    LastindexID = Reader("index_ID")
                    If InStr(ColumnList, Reader("Name"), CompareMethod.Text) > 0 Then
                        ' it's already there don't add it.


                    Else
                        If Len(ColumnList) > 0 Then
                            ColumnList = ColumnList & ","
                        End If
                        ColumnList = ColumnList & Reader("Name")
                    End If

                Loop
                If Len(ColumnList) > 0 Then
                    If IndexKeys.Contains(ColumnList) = False Then
                        IndexKeys.Add(ColumnList)
                    End If
                End If

                'Array.Sort(IndexKeys)

                Reader.Close()

                'SortedTypeList
                ' Dim SortedTypeList As New List(Of String)
                'Dim BadList As New List(Of String)
                For Each Columns As String In IndexKeys
                    Dim Signature As String = ""
                    Dim Keys() As String = Split(Columns, ",")

                    ' Array.Sort(Keys)

                    For Each Key As String In Keys
                        If Len(Signature) > 0 Then
                            Signature = Signature & ","
                        End If
                        Signature = Signature & GetDataTypeFromColumnName(Key, CodeTypeEnum.VB2005)
                        ' Debug.WriteLine(GetDataType(Key))
                    Next

                    Dim Signatures() As String = Split(Signature, ",")
                    Array.Sort(Signatures)

                    Signature = ""
                    For Each Key As String In Signatures
                        If Len(Signature) > 0 Then
                            Signature = Signature & ","
                        End If
                        Signature = Signature & Key
                    Next

                    If IndexKeysSortedTypeList.Contains(Signature) Then
                        BadList.Add(Signature)
                        IndexKeysSortedTypeList.Add(Signature)
                    Else
                        IndexKeysSortedTypeList.Add(Signature)
                    End If

                    Debug.WriteLine(Columns)
                Next
                'dr("ColumnName") = Column.Name
                'dr("DataType") = Column.GetColumnTypeName
            End If
        End If
        ' IndexKeys

        For Each Index As String In IndexKeys
            Dim RowIndex As Long = grd.Rows.Add()
            grd.Rows(RowIndex).Cells(0).Value = Index
        Next

        Connection.Close()

    End Sub

    Private Function GetDataTypeFromColumnName(ByVal ColumnName As String, ByVal CodeType As CodeTypeEnum) As String
        GetDataTypeFromColumnName = SQLDataTypeToGenType(ColumnList(ColumnName).GetColumnTypeName(), CodeType)
    End Function

    Private Sub Logit(ByVal s As String)
        MasterForm.txtOutput.Text = s & vbCrLf & MasterForm.txtOutput.Text
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="TargetPath"></param>
    ''' <returns>BackupFilePath that the original is moved to.</returns>
    ''' <remarks></remarks>
    Private Function BackupOriginalFile(ByVal TargetPath As String, ByVal CodeType As CodeTypeEnum) As String
        Dim BackupFilePath As String = Environment.CurrentDirectory & "\Backup\" & GetTargetFileName(CodeType)
        Dim Extension As String = Strings.Right(BackupFilePath, 2)
        Dim BackupFilePathWithoutExtension As String = Strings.Left(BackupFilePath, Len(BackupFilePath) - 2)

        BackupFilePath = BackupFilePathWithoutExtension & Now.ToString("yyyyMMdd.HHHHmmss.FFF.") & Extension

        System.IO.File.Move(TargetPath, BackupFilePath)

        Return BackupFilePath

    End Function

    Private Sub cmdGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGenerate.Click
        'OverwriteALL = False
        If MasterForm.txtPath.Text.Length = 0 Then
            MsgBox("Unable to generate please set the output directory.")
            Logit("Unable to generate please set the output directory.")
            MasterForm.TabControl1.SelectedIndex = 0
            MasterForm.txtPath.Focus()
            Exit Sub
        End If
        MasterForm.SaveCSI()
        Logit("Generation Started at " & Now.ToString)

        Dim s As String = ""

        'Dim pcg As New RawCreateScript(tbl.Name, "", "", DataTables("T" & tbl.ID), cboConnectionStringType.SelectedValue, txtConnectionString.Text, cboDatabaseType.SelectedValue, cboDBAccessMethod.SelectedValue, cboGridCodingStyle.SelectedValue, chkAddImports.Checked, txtMasterPageName.Text, chkUserMasterPages.Checked, chkIsExpress.Checked, cboCodeType.SelectedValue, txtProjectName.Text, cboKeyPassing.SelectedValue, cboButtonStyle.SelectedValue, cboCommentLevel.SelectedValue, cboDBAccessMethod.SelectedValue)
        'Support.DownloadFile(pcg, txtPath.Text & "\")
        'Dim IdentityColumnName As String = ""
        'Dim IdentityColumnType As String = "long"

        'For Each row As DataRow In dt.Rows
        '    If row("IsIdentity") Then
        '        IdentityColumnName = row("ColumnName")
        '    End If
        '    'AddColumn(row("ColumnName"), row("DataType"), row("AllowNulls"), row("ColumnSize"), "", row("ShowInDetailView"), row("IsIdentity"), False, False, row("ShowInMasterView"), row("SearchType"), row("IsGroupColumn"), "", "", "")
        'Next
        'IdentityColumnName = cboPrimaryKey.SelectedItem.ToString
        Dim CodeType As CodeTypeEnum
        'If MasterForm.cboCodeType.s Then
        Select Case MasterForm.cboCodeType.SelectedValue
            Case "VB2005"
                CodeType = CodeTypeEnum.VB2005
            Case "CS2005"
                CodeType = CodeTypeEnum.CS2005
        End Select
        For Each row As DataRow In dt.Rows
            'If row("columnName") = IdentityColumnName Then
            '    IdentityColumnType = SQLDataTypeToGenType(row("DataType"), CodeType)
            'End If

        Next

        Dim Filename As String = GetTargetFilePathName(CodeType)

        If False Then
            'MsgBox("Table : " & TableDatabaseObject.Name & " has no autonumber column")
            'Exit Sub
        Else

            Dim ClassName As String = txtPrefix.Text & TableDatabaseObject.Name


            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & "Imports Microsoft.VisualBasic" & vbCrLf
                    s = s & "Imports System.Data.SQLClient" & vbCrLf
                Case Else
                    s = s & "using System;" & vbCrLf
                    s = s & "using System.Collections.Generic;" & vbCrLf
                    s = s & "using System.Text;" & vbCrLf
                    s = s & "using System.Data.SqlClient;" & vbCrLf
            End Select
            s = s & vbCrLf


            If System.IO.File.Exists(Filename) Then
                Dim BackupFilePath As String = ""
                Try
                    BackupFilePath = BackupOriginalFile(Filename, CodeType)
                Catch ex As Exception

                End Try

                If Len(BackupFilePath) > 0 Then
                    s = s & Comment(CodeType, " Original file existed backup move to: " & BackupFilePath)
                    s = s & Comment(CodeType, "")
                End If
            End If

            Dim SharedConstructor As String = ""
            Dim RegularConstructor As String = ""

            If IndexKeys.Count = 1 Then
                s = s & Comment(CodeType, " " & IndexKeys.Count & " way to instantiate a " & ClassName & " object.")
            Else
                s = s & Comment(CodeType, " " & IndexKeys.Count & " ways to instantiate a " & ClassName & " object.")
            End If

            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    'do nothing
                Case Else
                    s = s & Comment(CodeType, " using PCG;  // PCG Namespace")
            End Select

            For Index As Long = 0 To IndexKeys.Count - 1
                Dim NeedsSharedFunction As Boolean = False
                If BadList.Contains(IndexKeysSortedTypeList(Index)) Then
                    'skip Badlist must be Static.
                    NeedsSharedFunction = True
                End If

                's = s & vbCrLf

                Dim Columns() As String = Split(IndexKeys(Index), ",")

                If NeedsSharedFunction Then
                    Select Case CodeType
                        Case CodeTypeEnum.VB2005
                            SharedConstructor = SharedConstructor & Comment(CodeType, " Dim " & TableDatabaseObject.Name & " As " & ClassName & " = " & ClassName & "." & GetStaticClassName(TableDatabaseObject, Columns) & "(" & ListDataTypes(CodeType, Columns) & ")")
                        Case Else
                            SharedConstructor = SharedConstructor & Comment(CodeType, " " & ClassName & " " & TableDatabaseObject.Name & " = " & ClassName & "." & GetStaticClassName(TableDatabaseObject, Columns) & "(" & ListDataTypes(CodeType, Columns) & ");")
                    End Select
                Else
                    Select Case CodeType
                        Case CodeTypeEnum.VB2005
                            RegularConstructor = RegularConstructor & Comment(CodeType, " Dim " & TableDatabaseObject.Name & " As New " & ClassName & "(" & ListDataTypes(CodeType, Columns) & ")")

                        Case Else
                            RegularConstructor = RegularConstructor & Comment(CodeType, " " & ClassName & " " & TableDatabaseObject.Name & " = new " & ClassName & "(" & ListDataTypes(CodeType, Columns) & ");")
                    End Select
                End If
            Next

            s = s & SharedConstructor
            s = s & RegularConstructor
            s = s & Comment(CodeType, "")
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Comment(CodeType, " '(optional) recommended record check by.")
                Case Else
                    s = s & Comment(CodeType, " //(optional) recommended record check by.")
            End Select
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Comment(CodeType, " If " & TableDatabaseObject.Name & ".RecordFound() Then ")
                Case Else
                    s = s & Comment(CodeType, " if (" & TableDatabaseObject.Name & ".RecordFound())")
                    s = s & Comment(CodeType, " {")
            End Select

            s = s & Comment(CodeType, "    ...")

            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Comment(CodeType, " End If")
                Case Else
                    s = s & Comment(CodeType, " }")
            End Select


            Dim Space As New Space()
            s = s & vbCrLf
            Select Case CodeType
                Case CodeTypeEnum.VB2005

                Case Else
                    s = s & "namespace PCG" & vbCrLf
                    s = s & "{" & vbCrLf
                    s = s & vbCrLf
            End Select


            s = s & Space.ToString & DeclarativeComment(CodeType, " <summary>")
            s = s & Space.ToString & DeclarativeComment(CodeType, " Class to read database table " & TableDatabaseObject.Name & ".")
            s = s & Space.ToString & DeclarativeComment(CodeType, " </summary>")
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & "Public Class " & ClassName & vbCrLf
                    s = s & "   Implements IDisposable" & vbCrLf
                Case Else
                    s = s & "public class " & ClassName & ": IDisposable" & vbCrLf
                    s = s & "{" & vbCrLf
            End Select

            Space.Inc()

            s = s & GetSubNew(Space, CodeType, ClassName)

            s = s & vbCrLf

            s = s & Space.ToString & Comment(CodeType, "Marked Protected to disallow allocation of empty objects outside this class.")
            s = s & Space.ToString & Comment(CodeType, "This is used inside for static Constructors when allocating new objects using different columns having the same type.")
            'todo Shared Function List.& vbCrLf 
            's = s & Space.ToString & Comment(CodeType, "1.) Public Shared Function NewCCV3LocationByMessageID()")
            '/todo.& vbCrLf 
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Space.ToString & "Protected Sub New()" & vbCrLf
                Case Else
                    s = s & Space.ToString & "protected " & ClassName & "()" & vbCrLf
                    s = s & Space.ToString & "{" & vbCrLf
            End Select
            Space.Inc()
            s = s & Space.ToString & Comment(CodeType, "Intentionally left blank")
            s = s & Space.ToString & Comment(CodeType, "Intentionally marked Protected")
            Space.Dec()
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Space.ToString & "End Sub" & vbCrLf
                Case Else
                    s = s & Space.ToString & "}" & vbCrLf
            End Select

            s = s & vbCrLf
            ' Populate Fields.
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Space.ToString & "Protected Sub PopulateFields(ByVal Reader As SqlDataReader)" & vbCrLf

                Case Else

                    s = s & Space.ToString & "protected void PopulateFields(SqlDataReader Reader)" & vbCrLf
                    s = s & Space.ToString & "{" & vbCrLf
            End Select
            Space.Inc()

            For Each row As DataRow In dt.Rows
                'If row("ColumnName") = IdentityColumnName Then
                '    Continue For
                'End If
                If row("AllowNulls") Then
                    s = s & vbCrLf
                    Select Case CodeType
                        Case CodeTypeEnum.VB2005
                            s = s & Space.ToString & "If IsDBNull(Reader(""" & row("ColumnName") & """)) Then" & vbCrLf
                            Space.Inc()
                            s = s & Space.ToString & txtPrivateMemberPrefix.Text & "IsNull" & row("ColumnName") & " = True" & vbCrLf
                            Space.Dec()
                            s = s & Space.ToString & "else" & vbCrLf
                            Space.Inc()
                            s = s & PrintVBRow(row, CodeType, Space)
                            Space.Dec()
                            's = s & "            " & row("ColumnName") & " = Reader(""" & row("ColumnName") & """)" & vbCrLf
                            s = s & Space.ToString & "end if " & vbCrLf

                        Case Else
                            s = s & Space.ToString & "if ( System.Convert.IsDBNull(Reader[""" & row("ColumnName") & """]) ) " & vbCrLf
                            s = s & Space.ToString & "{" & vbCrLf
                            Space.Inc()

                            s = s & Space.ToString & txtPrivateMemberPrefix.Text & "IsNull" & row("ColumnName") & " = true;" & vbCrLf
                            Space.Dec()

                            s = s & Space.ToString & "}" & vbCrLf
                            s = s & Space.ToString & "else" & vbCrLf
                            s = s & Space.ToString & "{" & vbCrLf
                            Space.Inc()
                            s = s & PrintCSRow(row, CodeType, Space)
                            Space.Dec()

                            s = s & Space.ToString & "}" & vbCrLf
                    End Select

                Else
                    s = s & vbCrLf
                    Select Case CodeType
                        Case CodeTypeEnum.VB2005
                            s = s & PrintVBRow(row, CodeType, Space)

                            's = s & "         " & row("ColumnName") & " = Reader(""" & row("ColumnName") & """)" & EndStatement(CodeType) & vbCrLf

                        Case Else
                            s = s & PrintCSRow(row, CodeType, Space)
                            ' s = s & "         " & row("ColumnName") & " = Reader[""" & row("ColumnName") & """]" & EndStatement(CodeType) & vbCrLf

                    End Select
                End If
            Next

            Space.Dec()
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Space.ToString & "End Sub" & vbCrLf

                Case Else
                    s = s & Space.ToString & "}" & vbCrLf

            End Select

            For Each row As DataRow In dt.Rows
                s = s & "" & vbCrLf
                If row("AllowNulls") Then
                    If False Then
                        'don't generate on primary key.
                    Else

                        Select Case CodeType
                            Case CodeTypeEnum.VB2005
                                s = s & Space.ToString & "Private " & txtPrivateMemberPrefix.Text & "IsNull" & row("ColumnName") & " as Boolean" & vbCrLf
                                s = s & Space.ToString & "Public ReadOnly Property IsNull" & row("ColumnName") & "() As Boolean" & vbCrLf
                                Space.Inc()
                                s = s & Space.ToString & "Get" & vbCrLf
                                Space.Inc()
                                s = s & Space.ToString & "Return " & txtPrivateMemberPrefix.Text & "IsNull" & row("ColumnName") & vbCrLf
                                Space.Dec()
                                s = s & Space.ToString & "End Get" & vbCrLf
                                Space.Dec()
                                s = s & Space.ToString & "End Property" & vbCrLf
                            Case Else
                                s = s & Space.ToString & "private Boolean " & txtPrivateMemberPrefix.Text & "IsNull" & row("ColumnName") & ";" & vbCrLf
                                s = s & Space.ToString & "public Boolean IsNull" & row("ColumnName") & vbCrLf
                                s = s & Space.ToString & "{" & vbCrLf
                                Space.Inc()
                                s = s & Space.ToString & "get { return " & txtPrivateMemberPrefix.Text & "IsNull" & row("ColumnName") & "; }" & vbCrLf
                                Space.Dec()
                                s = s & Space.ToString & "}" & vbCrLf
                        End Select
                        s = s & vbCrLf
                    End If
                End If

                Select Case CodeType
                    Case CodeTypeEnum.VB2005
                        s = s & Space.ToString & "Private " & txtPrivateMemberPrefix.Text & row("ColumnName") & " As " & SQLDataTypeToGenType(row("DataType"), CodeType) & vbCrLf
                    Case Else
                        s = s & Space.ToString & "private " & SQLDataTypeToGenType(row("DataType"), CodeType) & " " & txtPrivateMemberPrefix.Text & row("ColumnName") & ";" & vbCrLf
                End Select
                Select Case CodeType
                    Case CodeTypeEnum.VB2005
                        s = s & Space.ToString & "Public Readonly Property " & row("ColumnName") & "() As " & SQLDataTypeToGenType(row("DataType"), CodeType) & vbCrLf
                    Case Else
                        s = s & Space.ToString & "public " & SQLDataTypeToGenType(row("DataType"), CodeType) & " " & row("ColumnName") & vbCrLf
                        s = s & Space.ToString & "{" & vbCrLf

                End Select
                Space.Inc()
                Select Case CodeType
                    Case CodeTypeEnum.VB2005
                        s = s & Space.ToString & "Get" & vbCrLf
                        Space.Inc()
                        s = s & Space.ToString & "Return " & txtPrivateMemberPrefix.Text & row("ColumnName") & "" & vbCrLf
                        Space.Dec()
                        s = s & Space.ToString & "End Get" & vbCrLf
                    Case Else
                        s = s & Space.ToString & "get { return " & txtPrivateMemberPrefix.Text & row("ColumnName") & "; }" & vbCrLf
                End Select

                'Select Case CodeType
                '    Case CodeTypeEnum.VB2005
                '        s = s & Space.ToString & "Set(ByVal value As " & SQLDataTypeToGenType(row("DataType"), CodeType) & ")" & vbCrLf
                '        Space.Inc()
                '        s = s & Space.ToString & txtPrivateMemberPrefix.Text & row("ColumnName") & " = value" & vbCrLf
                '        Space.Dec()
                '        s = s & Space.ToString & "End Set" & vbCrLf
                '    Case Else
                '        s = s & Space.ToString & "set { " & txtPrivateMemberPrefix.Text & row("ColumnName") & " = value; }" & vbCrLf
                'End Select
                Space.Dec()
                Select Case CodeType
                    Case CodeTypeEnum.VB2005
                        s = s & Space.ToString & "End Property" & vbCrLf
                    Case Else

                        s = s & Space.ToString & "}" & vbCrLf
                End Select

            Next
            s = s & vbCrLf
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & Space.ToString & "Private mRecordFound As Boolean = False" & vbCrLf
                    s = s & Space.ToString & "Public Function RecordFound() As Boolean" & vbCrLf
                    Space.Inc()
                    s = s & Space.ToString & "Return mRecordFound" & vbCrLf
                    Space.Dec()
                    s = s & Space.ToString & "End Function" & vbCrLf
                Case Else
                    s = s & Space.ToString & "private Boolean mRecordFound = false;" & vbCrLf
                    s = s & Space.ToString & "public Boolean RecordFound() " & vbCrLf
                    s = s & Space.ToString & "{" & vbCrLf
                    Space.Inc()
                    s = s & Space.ToString & "return mRecordFound;" & vbCrLf
                    Space.Dec()
                    s = s & Space.ToString & "}" & vbCrLf
            End Select




            s = s & vbCrLf

            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & "#Region "" IDisposable Section """ & vbCrLf

                    s = s & "    Private disposedValue As Boolean = False        ' To detect redundant calls" & vbCrLf
                    s = s & "    ' IDisposable" & vbCrLf
                    s = s & "    Protected Overridable Sub Dispose(ByVal disposing As Boolean)" & vbCrLf
                    s = s & "        If Not Me.disposedValue Then" & vbCrLf
                    s = s & "            If disposing Then" & vbCrLf
                    s = s & "                ' TODO: free other state (managed objects)." & vbCrLf
                    s = s & "            End If" & vbCrLf
                    s = s & "" & vbCrLf
                    s = s & "            ' TODO: free your own state (unmanaged objects)." & vbCrLf
                    s = s & "            ' TODO: set large fields to null." & vbCrLf
                    s = s & "        End If" & vbCrLf
                    s = s & "        Me.disposedValue = True" & vbCrLf
                    s = s & "    End Sub" & vbCrLf
                    s = s & "" & vbCrLf
                    s = s & "#Region "" IDisposable Support """ & vbCrLf
                    s = s & "    ' This code added by Visual Basic to correctly implement the disposable pattern." & vbCrLf
                    s = s & "    Public Sub Dispose() Implements IDisposable.Dispose" & vbCrLf
                    s = s & "        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above." & vbCrLf
                    s = s & "        Dispose(True)" & vbCrLf
                    s = s & "        GC.SuppressFinalize(Me)" & vbCrLf
                    s = s & "    End Sub" & vbCrLf
                    s = s & "#End Region" & vbCrLf
                    s = s & "#End Region" & vbCrLf
                Case Else
                    s = s & "#region "" IDisposable Section """ & vbCrLf
                    s = s & "#region "" IDisposable Support """ & vbCrLf
                    s = s & "" & vbCrLf

                    s = s & "// Track whether Dispose has been called." & vbCrLf
                    s = s & "private bool disposed = false;" & vbCrLf
                    s = s & "" & vbCrLf

                    s = s & "        // Implement IDisposable." & vbCrLf
                    s = s & "        // Do not make this method virtual." & vbCrLf
                    s = s & "        // A derived class should not be able to override this method." & vbCrLf
                    s = s & "        public void Dispose()" & vbCrLf
                    s = s & "        {" & vbCrLf
                    s = s & "            Dispose(true);" & vbCrLf
                    s = s & "            // This object will be cleaned up by the Dispose method." & vbCrLf
                    s = s & "            // Therefore, you should call GC.SupressFinalize to" & vbCrLf
                    s = s & "            // take this object off the finalization queue" & vbCrLf
                    s = s & "            // and prevent finalization code for this object" & vbCrLf
                    s = s & "            // from executing a second time." & vbCrLf
                    s = s & "            GC.SuppressFinalize(this);" & vbCrLf
                    s = s & "        }" & vbCrLf
                    s = s & "#endregion " & vbCrLf

                    s = s & "" & vbCrLf
                    s = s & "        // Dispose(bool disposing) executes in two distinct scenarios." & vbCrLf
                    s = s & "        // If disposing equals true, the method has been called directly" & vbCrLf
                    s = s & "        // or indirectly by a user's code. Managed and unmanaged resources" & vbCrLf
                    s = s & "        // can be disposed." & vbCrLf
                    s = s & "        // If disposing equals false, the method has been called by the" & vbCrLf
                    s = s & "        // runtime from inside the finalizer and you should not reference" & vbCrLf
                    s = s & "        // other objects. Only unmanaged resources can be disposed." & vbCrLf
                    s = s & "        protected virtual void Dispose(bool disposing)" & vbCrLf
                    s = s & "        {" & vbCrLf
                    s = s & "            // Check to see if Dispose has already been called." & vbCrLf
                    s = s & "            if(!this.disposed)" & vbCrLf
                    s = s & "            {" & vbCrLf
                    s = s & "                // If disposing equals true, dispose all managed" & vbCrLf
                    s = s & "                // and unmanaged resources." & vbCrLf
                    s = s & "                if(disposing)" & vbCrLf
                    s = s & "                {" & vbCrLf
                    s = s & "                    // Dispose managed resources." & vbCrLf
                    s = s & "                }" & vbCrLf
                    s = s & "" & vbCrLf
                    s = s & "                // Call the appropriate methods to clean up" & vbCrLf
                    s = s & "                // unmanaged resources here." & vbCrLf
                    s = s & "                // If disposing is false," & vbCrLf
                    s = s & "                // only the following code is executed." & vbCrLf
                    s = s & "" & vbCrLf
                    s = s & "                // Note disposing has been done." & vbCrLf
                    s = s & "                disposed = true;" & vbCrLf
                    s = s & "" & vbCrLf
                    s = s & "            }" & vbCrLf
                    s = s & "        }" & vbCrLf
                    s = s & "#endregion " & vbCrLf

            End Select

            s = s & vbCrLf
            Select Case CodeType
                Case CodeTypeEnum.VB2005
                    s = s & "End Class" & vbCrLf
                Case Else
                    s = s & "}" & vbCrLf
            End Select
        End If

        Select Case CodeType
            Case CodeTypeEnum.VB2005

            Case Else
                s = s & "}" & vbCrLf
        End Select

        If System.IO.Directory.Exists(MasterForm.txtPath.Text) = False Then
            If MsgBox("Directory : " & MasterForm.txtPath.Text & " does not exist do you want to create it?", MsgBoxStyle.YesNoCancel, "Create Directory " & MasterForm.txtPath.Text) = MsgBoxResult.Yes Then
                System.IO.Directory.CreateDirectory(MasterForm.txtPath.Text)
            Else
                Exit Sub
            End If
        End If



        Dim fs As New System.IO.FileStream(Filename, FileMode.Create)
        Dim AE As New ASCIIEncoding()
        Dim out As Byte() = AE.GetBytes(s)
        fs.Write(out, 0, out.Length)
        fs.Close()
        Logit("Class " & txtPrefix.Text & TableDatabaseObject.Name & " to " & Filename)

        Logit("Generation Complete " & Now.ToString)
        MsgBox("Generation Complete")
    End Sub

    Private Function GetTargetFileName(ByVal CodeType As CodeTypeEnum) As String
        Dim Filename As String = txtPrefix.Text & TableDatabaseObject.Name

        Select Case CodeType
            Case CodeTypeEnum.VB2005
                Filename = Filename & ".vb"
            Case Else
                Filename = Filename & ".cs"
        End Select
        Return Filename
    End Function

    Private Function GetTargetFilePathName(ByVal CodeType As CodeTypeEnum) As String
        Dim Filename As String = MasterForm.txtPath.Text
        If Strings.Right(Filename, 1) = "\" Then
        Else
            Filename = Filename & "\"
        End If

        Filename = Filename & GetTargetFileName(CodeType)
        Return Filename
    End Function

    Private Function DeclarativeComment(ByVal CodeType As CodeTypeEnum, ByVal s As String) As String
        Select Case CodeType
            Case CodeTypeEnum.VB2005
                Return "'''" & s & vbCrLf
            Case CodeTypeEnum.CS2005
                Return "///" & s & vbCrLf
        End Select
        Return ""
    End Function

    Private Function Comment(ByVal CodeType As CodeTypeEnum, ByVal s As String)
        Select Case CodeType
            Case CodeTypeEnum.VB2005
                Return "'" & s & vbCrLf
            Case CodeTypeEnum.CS2005
                Return "//" & s & vbCrLf
        End Select
        Return ""
    End Function

    Private Function ListDataTypes(ByVal CodeType As CodeTypeEnum, ByVal Columns() As String) As String
        ListDataTypes = ""
        For Each Column As String In Columns
            If Len(ListDataTypes) > 0 Then
                ListDataTypes = ListDataTypes & ","
            End If

            ListDataTypes = ListDataTypes & GetDataTypeFromColumnName(Column, CodeType)
        Next
    End Function

    Private Function GetSubNew(ByVal space As Space, ByVal Codetype As CodeTypeEnum, ByVal ClassName As String) As String

        'Public IndexKeys As New List(Of String)
        'Public IndexKeysSortedTypeList As New List(Of String)
        'Public BadList As New List(Of String)
        Dim s As String = ""
        For Index As Long = 0 To IndexKeys.Count - 1
            Dim NeedsSharedFunction As Boolean = False
            If BadList.Contains(IndexKeysSortedTypeList(Index)) Then
                'skip Badlist must be Static.
                NeedsSharedFunction = True
            End If

            s = s & vbCrLf

            Dim Columns() As String = Split(IndexKeys(Index), ",")
            'Select Case Codetype
            '    Case CodeTypeEnum.VB2005
            If NeedsSharedFunction Then

                '    public static CDocument CDocumentX()
                '{
                s = s & space.ToString & DeclarativeComment(Codetype, "<summary>")
                s = s & space.ToString & DeclarativeComment(Codetype, "Initializes a new instance of the " & ClassName & " class.")
                s = s & space.ToString & DeclarativeComment(Codetype, "</summary>")
                For Each ColumnName As String In Columns
                    '                    s = s & space.ToString & DeclarativeComment(Codetype, "<param name=""" & ColumnName & """></param>")
                    s = s & space.ToString & DeclarativeComment(Codetype, "<param name=""" & ColumnName & """>Search Criteria " & ColumnName & " column from the database." & "</param>")
                Next
                s = s & space.ToString & DeclarativeComment(Codetype, "<returns>")
                s = s & space.ToString & DeclarativeComment(Codetype, "A new " & ClassName & " object.")
                s = s & space.ToString & DeclarativeComment(Codetype, "</returns>")

                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        s = s & space.ToString & "Public Shared Function New"
                        s = s & GetStaticClassName(TableDatabaseObject, Columns)

                    Case CodeTypeEnum.CS2005
                        s = s & space.ToString & "public static " & ClassName & " New"
                        s = s & GetStaticClassName(TableDatabaseObject, Columns)

                End Select
                's = s & space.ToString & "Public Shared Function New"
                's = s & GetStaticClassName(TableDatabaseObject, Columns)
                'If TableDatabaseObject.Schema.ToUpper = "DBO" Then
                '    'do nothing
                'Else
                '    s = s & TableDatabaseObject.Schema
                'End If
                's = s & TableDatabaseObject.Name
                s = s & "("
            Else
                s = s & space.ToString & DeclarativeComment(Codetype, "<summary>")
                s = s & space.ToString & DeclarativeComment(Codetype, "Initializes a new instance of the " & ClassName & " class.")
                s = s & space.ToString & DeclarativeComment(Codetype, "</summary>")
                For Each ColumnName As String In Columns
                    s = s & space.ToString & DeclarativeComment(Codetype, "<param name=""" & ColumnName & """>Search Criteria " & ColumnName & " column from the database." & "</param>")
                Next
                's = s & space.ToString & DeclarativeComment(Codetype, "<returns>")
                's = s & space.ToString & DeclarativeComment(Codetype, "A new " & ClassName & " object.")
                's = s & space.ToString & DeclarativeComment(Codetype, "</returns>")
                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        s = s & space.ToString & "Public Sub New("
                    Case Else
                        s = s & space.ToString & "public " & ClassName & "("
                End Select

            End If


            Dim ParameterList As String = ""
            For Each ColumnName As String In Columns
                If Len(ParameterList) > 0 Then
                    ParameterList = ParameterList & ", "
                End If

                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        ParameterList = ParameterList & "ByVal " & ColumnName & " As " & GetDataTypeFromColumnName(ColumnName, Codetype)

                    Case Else
                        ParameterList = ParameterList & GetDataTypeFromColumnName(ColumnName, Codetype) & " " & ColumnName
                End Select
            Next

            s = s & ParameterList

            s = s & ")"

            Dim g As Guid = Guid.NewGuid()

            If NeedsSharedFunction Then
                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        s = s & " As " & ClassName
                    Case Else
                        'do nothing
                End Select

            Else
                ' do nothing
            End If

            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    ' do nothing
                Case Else
                    s = s & vbCrLf
                    s = s & space.ToString & "{"
            End Select

            s = s & vbCrLf
            '    Case Else
            '        s = s & space.ToString & "public " & txtPrefix.Text & TableDatabaseObject.Name & "( "
            '        Dim ParameterList As String = ""
            '        For Each ColumnName As String In Columns
            '            If Len(ParameterList) > 0 Then
            '                ParameterList = ParameterList & ","
            '            End If
            '            ParameterList = ParameterList & GetDataTypeFromColumnName(ColumnName) & " " & ColumnName
            '        Next
            '        s = s & ParameterList
            '        s = s & " )" & vbCrLf
            '        s = s & space.ToString & "{" & vbCrLf

            'End Select
            's = s & "" & vbCrLf
            space.Inc()
            If NeedsSharedFunction Then
                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        s = s & space.ToString & "New" & GetStaticClassName(TableDatabaseObject, Columns) & " = New " & ClassName
                    Case Else
                        s = s & space.ToString & ClassName & " InstanceOf" & ClassName & " = new " & ClassName & "();"
                End Select
                s = s & vbCrLf
            End If

            ' Sub New


            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "' ConfigurationManager' is not a member of 'Configuration'" & vbCrLf
                    s = s & space.ToString & "' Add a reference to System.Configuration" & vbCrLf
                Case Else
                    s = s & space.ToString & "// Error message: 1" & vbCrLf
                    s = s & space.ToString & "// ***The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration'(are you missing an assembly reference?)" & vbCrLf
                    s = s & space.ToString & "// Add a project reference to System.Configuration" & vbCrLf
                    s = s & space.ToString & "// From the Menu above choose:  Project->Add Reference" & vbCrLf
                    s = s & space.ToString & "// Under the .NET Tab choose: Component Name: System.Configuration, then click OK." & vbCrLf
                    s = s & space.ToString & "// Error message 2:" & vbCrLf
                    s = s & space.ToString & "// ***Null Reference Exception was unhandled:  " & vbCrLf
                    s = s & space.ToString & "// ***Object reference not set to an instance of an object." & vbCrLf
                    s = s & space.ToString & "// The connection string is not defined in the app.config or web.config" & vbCrLf
            End Select

            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "Dim Connection As New SqlConnection(" & GetCS(MasterForm.cboConnectionStringType.SelectedValue, MasterForm.txtConnectionString.Text) & ")" & vbCrLf
                Case Else
                    s = s & space.ToString & "SqlConnection Connection = new SqlConnection(" & GetCS(MasterForm.cboConnectionStringType.SelectedValue, MasterForm.txtConnectionString.Text, Codetype) & ");" & vbCrLf
            End Select
            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "Connection.Open()" & vbCrLf

                Case Else
                    s = s & space.ToString & "Connection.Open();" & vbCrLf

            End Select
            s = s & "" & vbCrLf
            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "Dim Command As New SqlCommand("""
                    'select * from " & TableDatabaseObject.Schema & "." & TableDatabaseObject.Name & " where " & IdentityColumnName & " = @" & IdentityColumnName 

                Case Else
                    s = s & space.ToString & "SqlCommand Command = new SqlCommand("""
            End Select

            'sql statement
            s = s & "select * from [" & TableDatabaseObject.Schema & "].[" & TableDatabaseObject.Name & "] where "

            Dim WhereClause As String = ""
            For Each ColumnName As String In Columns
                If Len(WhereClause) > 0 Then
                    WhereClause = WhereClause & " and "
                End If
                WhereClause = WhereClause & ColumnName & " = @" & ColumnName
            Next

            s = s & WhereClause
            '/sql statement
            s = s & """, Connection)" & EndStatement(Codetype) & vbCrLf
            'Select Case Codetype
            '    Case CodeTypeEnum.VB2005
            '        s = s & space.ToString & "Dim Command As New SqlCommand(""select * from " & TableDatabaseObject.Schema & "." & TableDatabaseObject.Name & " where " & IdentityColumnName & " = @" & IdentityColumnName & """, Connection)" & vbCrLf

            '    Case Else
            '        s = s & space.ToString & "SqlCommand Command = new SqlCommand(""select * from " & TableDatabaseObject.Schema & "." & TableDatabaseObject.Name & " where " & IdentityColumnName & " = @" & IdentityColumnName & """, Connection);" & vbCrLf
            'End Select

            For Each ColumnName As String In Columns
                s = s & space.ToString & "Command.Parameters.AddWithValue(""@" & ColumnName & """, " & ColumnName & ")" & EndStatement(Codetype) & vbCrLf
            Next

            s = s & "" & vbCrLf
            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "Dim Reader As SqlDataReader = Command.ExecuteReader" & vbCrLf
                Case Else
                    s = s & space.ToString & "SqlDataReader Reader = Command.ExecuteReader();" & vbCrLf
            End Select

            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "If Reader.Read Then" & vbCrLf

                Case Else
                    s = s & space.ToString & "if ( Reader.Read() )" & vbCrLf
                    s = s & space.ToString & "{" & vbCrLf

            End Select
            space.Inc()


            s = s & space.ToString
            If NeedsSharedFunction Then
                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        s = s & "New" & GetStaticClassName(TableDatabaseObject, Columns) & "."
                    Case Else
                        s = s & "InstanceOf" & ClassName & "."

                End Select

            End If

            s = s & "PopulateFields(Reader)" & EndStatement(Codetype) & vbCrLf

            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString
                Case Else
                    s = s & space.ToString
            End Select

            If NeedsSharedFunction Then
                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        s = s & "New" & GetStaticClassName(TableDatabaseObject, Columns) & "."

                    Case Else
                        s = s & "InstanceOf" & ClassName & "."

                End Select
            End If

            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & "mRecordFound = True" & EndStatement(Codetype) & vbCrLf
                Case Else
                    s = s & "mRecordFound = true" & EndStatement(Codetype) & vbCrLf
            End Select

            space.Dec()
            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    s = s & space.ToString & "End If" & vbCrLf
                Case Else
                    s = s & space.ToString & "}" & vbCrLf
            End Select

            s = s & space.ToString & "Reader.Close()" & EndStatement(Codetype) & vbCrLf
            s = s & space.ToString & "Connection.Close()" & EndStatement(Codetype) & vbCrLf

            If NeedsSharedFunction Then
                Select Case Codetype
                    Case CodeTypeEnum.VB2005
                        'do nothing
                    Case Else
                        s = s & vbCrLf
                        s = s & space.ToString & "return InstanceOf" & ClassName & ";" & vbCrLf

                End Select
            End If
            space.Dec()
            Select Case Codetype
                Case CodeTypeEnum.VB2005
                    If NeedsSharedFunction Then
                        s = s & space.ToString & "End Function" & vbCrLf
                    Else
                        s = s & space.ToString & "End Sub" & vbCrLf
                    End If

                Case Else
                    s = s & space.ToString & "}" & vbCrLf
            End Select
        Next
        Return s
    End Function

    Private Function GetStaticClassName(ByVal TableDatabaseObject As DatabaseObject, ByVal Columns() As String) As String
        Dim s As String = ""
        If TableDatabaseObject.Schema.ToUpper = "DBO" Then
            'do nothing
        Else
            s = s & TableDatabaseObject.Schema
        End If
        s = s & TableDatabaseObject.Name

        For Each Column As String In Columns
            s = s & "By" & Column
        Next

        Return s
    End Function


    Private Sub cmdCloseButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCloseButton.Click
        Dim parent As TabControl = Me.Parent
        parent.TabPages.Remove(Me)
    End Sub

    Private Sub cmdAddNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAddNew.Click
        Dim frm As New frmConstructorList(ColumnList.Keys().ToArray)
        frm.ShowDialog()

        Dim Keys() As String = frm.ConstructorColumnsSelected

        If Keys Is Nothing = False Then



            Dim Signature As String = ""
            Dim IndexKey As String = ""
            For Each Key As String In Keys
                If Len(Signature) > 0 Then
                    Signature = Signature & ","
                    IndexKey = IndexKey & ","
                End If
                Signature = Signature & GetDataTypeFromColumnName(Key, CodeTypeEnum.VB2005)
                IndexKey = IndexKey & Key
                ' Debug.WriteLine(GetDataType(Key))
            Next

            Dim Signatures() As String = Split(Signature, ",")
            Array.Sort(Signatures)

            Signature = ""
            For Each Key As String In Signatures
                If Len(Signature) > 0 Then
                    Signature = Signature & ","
                End If
                Signature = Signature & Key
            Next

            If IndexKeys.Contains(IndexKey) Then
                'already there exit
                Exit Sub
            Else
                IndexKeys.Add(IndexKey)
                If IndexKeysSortedTypeList.Contains(Signature) Then
                    IndexKeysSortedTypeList.Add(Signature)
                    If BadList.Contains(Signature) Then
                        ' do nothing already there.
                    Else
                        BadList.Add(Signature)
                    End If
                Else
                    IndexKeysSortedTypeList.Add(Signature)
                End If
            End If

            'add to grid.
            Dim RowIndex As Long = grd.Rows.Add()
            grd.Rows(RowIndex).Cells(0).Value = IndexKey

            'Public IndexKeys As New List(Of String)
            'Public IndexKeysSortedTypeList As New List(Of String)
            'Public ColumnList As New Dictionary(Of String, Column)
            'Public BadList As New List(Of String)
        End If

    End Sub
End Class
